import { __private, _decorator, Camera, Component, instantiate, Node, Prefab } from 'cc';
import { UIBase } from './UIBase';
import { ResMgr } from '../ResMgr';
const { ccclass, property } = _decorator;

@ccclass('UIRoot')
export class UIRoot extends Component {

    private static _inst: UIRoot;
    public static get inst(): UIRoot {
        return this._inst;
    }

    @property({ type: Camera })
    public UICam: Camera = null;


    protected onLoad(): void {
        UIRoot._inst = this;
    }

    start() {

    }

    update(deltaTime: number) {

    }

    public OpenUI<T extends UIBase>(type: __private._types_globals__Constructor<T>,
        onComplete: ((err: Error | null, data: T) => void) = null,
        paths: string = null) {

        let ui = this.FindUI(type);
        if (ui) {
            ui.Show();
            if (onComplete) onComplete(null, ui);
            return;
        }

        let name: string = type.name;
        let path = paths ? paths : "Bundle/UI/" + name;
        ResMgr.inst.load(path, Prefab, null, (err, prefab) => {
            let newUI = instantiate(prefab);
            this.node.addChild(newUI);
            newUI.getComponent(type).Show();
        });
    }

    public FindUI<T extends UIBase>(type: __private._types_globals__Constructor<T>): T {
        for (let i = 0; i < this.node.children.length; ++i) {
            let c = this.node.children[i];
            let com = c.getComponent(type);
            if (com) {
                return com;
            }
        }
    }

    public CloseUI<T extends UIBase>(type: __private._types_globals__Constructor<T>) {
        let ui = this.FindUI(type);
        if (ui) {
            ui.Close();
        }
    }

    public HideUI<T extends UIBase>(type: __private._types_globals__Constructor<T>) {
        let ui = this.FindUI(type);
        if (ui) {
            ui.Hide();
        }
    }
}


